import React, { useState } from 'react';
import Joi from 'joi-browser';
import Input from './input';
function LoginForm() {
  const schema = {
    username: Joi.string().required().label('Username'),
    password: Joi.string().required().label('Password'),
  };
  const [account, setAccount] = useState({
    username: '',
    password: '',
  });
  const [errors, setErrors] = useState({});
  const handleChange = ({ currentTarget: input }) => {
    const errorsMessage = validateProperty(input);
    if (errorsMessage) errors[input.name] = errorsMessage;
    else delete errors[input.name];
    const { name, value } = input;
    const accountClone = { ...account };
    accountClone[name] = value;
    setAccount(accountClone);
    setErrors(errors);
  };
  const validate = () => {
    const options = {
      //设置多个验证
      abortEarly: false,
    };
    const { error } = Joi.validate(account, schema, options);

    /**
     * Joi校验库实现方式
     */
    if (!error) return null;
    const errors = {};
    //使用path下的第0位作为键名, 并赋予错误提示信息
    for (const item of error.details) errors[item.path[0]] = item.message;
    return errors;

    /*
    手动实现方式
    if (account.username.trim() === '')
      errors.username = 'Username is required.';
    if (account.password.trim() === '')
      errors.password = 'Password is required.';
    return Object.keys(errors).length === 0 ? null : errors; */
  };

  const validateProperty = ({ name, value }) => {
    const obj = {
      [name]: value,
    };
    const schemaChange = { [name]: schema[name] };
    const { error } = Joi.validate(obj, schemaChange);
    return error ? error.details[0].message : null;
    /*
    手动实现方式
    if (name === 'username') {
      if (value.trim() === '') return 'Username is required.';
    }
    if (name === 'password') {
      if (value.trim() === '') return 'password is required.';
    } */
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    const errors = validate();
    setErrors(errors || {});
    if (errors) return;
    console.log('Submitted');
  };
  return (
    <div>
      <h1>Login</h1>
      <form onSubmit={handleSubmit}>
        <Input
          name="username"
          value={account.username}
          label="Username"
          onChange={handleChange}
          error={errors.username}
        />
        <Input
          name="password"
          value={account.password}
          label="Password"
          onChange={handleChange}
          error={errors.password}
        />
        <button disabled={validate()} className="btn btn-primary">
          Login
        </button>
      </form>
    </div>
  );
}

export default LoginForm;
